using System;
using System.IO;
using System.Web;
using System.Data;
using System.Xml;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Web.Security;
using System.Web.Services;
using ACM.cmsarea08;
using ACM.cmsarea08.Administration.Core;



namespace ACM.cmsarea08.Administration {
	public class XmlServer : System.Web.Services.WebService {
		private Administration.Core.DBClass dclass;
			
		public XmlServer() {
			dclass = new Administration.Core.DBClass();
		}
		
		[ WebMethod(Description="getCategoriesbySec",EnableSession=true)]
		public XmlDocument getCategoriesbySec(string lingua,string sezione,bool managed) {
			DataSet duser = dclass.getAdminContentSelected(lingua,sezione,ContentManagerTypes.Categorie,managed);
			if(duser==null) 
				return new XmlDocument();			
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(duser.GetXml());
			return outd;			
		}

		[ WebMethod(Description="getContentssbySecCat",EnableSession=true)]
		public XmlDocument getContentssbySecCat(string lingua, string sezione,string categoria,bool managed) {
			DataSet duser = dclass.getAdminArticleSelected(lingua,sezione,categoria,managed);
			if(duser==null) 
				return new XmlDocument();
			
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(duser.GetXml());
			return outd;			
		}
		
		[ WebMethod(Description="getBlockViews",EnableSession=true)]
		public XmlDocument getBlockViews(){
			DataSet dvs = dclass.ExecuteDataset("select id,titolo from "+dclass.TablePrefix +"blocco_visivo where enabled='1' order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}
		
		[ WebMethod(Description="getModules",EnableSession=true)]
		public XmlDocument getModules(){
			DataSet dvs = dclass.ExecuteDataset("select id,titolo from "+dclass.TablePrefix +"moduli where enabled='1' order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}
		[ WebMethod(Description="getMenu",EnableSession=true)]
		public XmlDocument getMenu(){
			DataSet dvs = dclass.ExecuteDataset("select modio.id,modio.titolo from "+dclass.TablePrefix +"moduli as modio " +
			                                    "left join "+dclass.TablePrefix +"componenti as compio on modio.id_componente=compio.id " +
			                                    " where modio.enabled='1' and compio.ismenu='1' order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	
		[ WebMethod(Description="getVMenu",EnableSession=true)]
		public XmlDocument getVMenu(string idmem){
			DataSet dvs = dclass.ExecuteDataset("select cast(concat(menu_contenitore,'~',id) as char) ,titolo from "+dclass.TablePrefix +"menu_elemento " +
			                                    " where enabled='1' and menu_contenitore='"+idmem+"' order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}		
		[ WebMethod(Description="getContextItemTitle",EnableSession=true)]
		public string getContextItemTitle(string id, string checker){
			string table = "";
			string column = "";
			id = HttpUtility.UrlDecode(id);
			checker = HttpUtility.UrlDecode(checker);
			switch(checker.ToUpper()) {
				case "0#": table = "moduli"; column = "titolo";break;
				case "M#": table = "moduli"; column = "titolo";break;				
				case "0V#": table = "menu_elemento"; column = "titolo";break;								
				case "1#A": table = "contenuti"; column = "titolo";
					if(id.IndexOf('~')!=-1) 
						id= id.Substring(id.LastIndexOf('~')+1);
					break;
				case "1#C": table = "contenuti_manager"; column = "titolo";
					if(id.IndexOf('~')!=-1) 
						id= id.Substring(id.LastIndexOf('~')+1);
					break;
				case "1#S": table = "contenuti_manager"; column = "titolo";break;																
			}
			string errore ="";
			object o = dclass.ExecuteScalar_Logged("select "+column+" from "+dclass.TablePrefix +table+" " +
			                   " where id='"+id+"' limit 1",out errore);
			string testo = "";
			if(o==null) testo = "";
			if(o!=null) {
				if(o is byte[]) testo = System.Text.Encoding.UTF8.GetString((byte[])o);
				else testo = o.ToString();
			}
			return testo;
		}				
		[ WebMethod(Description="getModulesElement",EnableSession=true)]
		public XmlDocument getModulesElement(string idmod){
			DataSet dvs = dclass.ExecuteDataset("SELECT if(blockview_control is null,'',blockview_control) as control, " + 
     											" if(mainbody_control is null,'',mainbody_control)  as body FROM "+dclass.TablePrefix +"componenti " +
     											" where id = (select id_componente from "+dclass.TablePrefix +"moduli where id="+idmod+" limit 1) ;");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	
		
		[ WebMethod(Description="getSection",EnableSession=true)]
		public XmlDocument getSection(){
			DataSet dvs = dclass.ExecuteDataset("select id,titolo from "+dclass.TablePrefix +"contenuti_manager " +
			                                    "where " +
			                                    "tipo='S'  order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	
		[ WebMethod(Description="getCategory",EnableSession=true)]
		public XmlDocument getCategory(string idsec){
			DataSet dvs = dclass.ExecuteDataset("select id,titolo from "+dclass.TablePrefix +"contenuti_manager where tipo='C' and figliodi="+idsec+" order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}
		[ WebMethod(Description="getCategoryCC",EnableSession=true)]
		public XmlDocument getCategoryCC(string idsec){
			DataSet dvs = dclass.ExecuteDataset("select cast(concat(figliodi,'~',id) as char) as id ,titolo from "+dclass.TablePrefix +"contenuti_manager where tipo='C' and figliodi="+idsec+" order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}		

		[ WebMethod(Description="getArticoli",EnableSession=true)]
		public XmlDocument getArticoli(string idcat){
			DataSet dvs = dclass.ExecuteDataset("select id,titolo from "+dclass.TablePrefix +"contenuti where enabled='1' and cat_id="+idcat+" order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	
		[ WebMethod(Description="getArticoliCC",EnableSession=true)]
		public XmlDocument getArticoliCC(string idcat){
			DataSet dvs = dclass.ExecuteDataset("select cast(concat(sez_id,'~',cat_id,'~',id) as char) as id,titolo from "+dclass.TablePrefix +"contenuti where enabled='1' and cat_id="+idcat+" order by titolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}			
		[ WebMethod(Description="getHomePageLayout",EnableSession=true)]
		public XmlDocument getHomePageLayout(){
			DataSet dvs = dclass.ExecuteDataset("select id,itemtype,itemid,ordine,titolo from "+dclass.TablePrefix +"hplayout order by ordine asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}		

		[ WebMethod(Description="setHomePageLayout",EnableSession=true)]
		public int setHomePageLayout(string newlayout){
			//intepreta la stringa... 
			//sample: ['BV~50','MDC~72','CT~28']
			try {
			string layout = newlayout.Substring(1);
			//layout = layout.Replace("\'","");
			layout = layout.Substring(0,layout.Length-1);
			string[] lay_item = new string[0];
			if(layout.IndexOf(',')==-1) 
				lay_item = new string[1] {layout.Trim() };
			else
				lay_item = layout.Split(',');
			//se + di un elemento ..
			string query = "";
			for(int i = 0 ; i<lay_item.Length; i++) {
				string[] item = new string[0];
				if(lay_item[i].Trim().IndexOf('~')==-1) continue;
				item = lay_item[i].Trim().Split('~');
				if(item.Length>=3) 
				query += string.Format("insert into {0}hplayout (itemtype,itemid,ordine,titolo,enabled) " +
					                       "values('{1}',{2},{3},'{4}','1'); ", dclass.TablePrefix,item[0], item[1],i,item[2]) ;
			}
			if(query.Trim()!="") {
				//elimina attuale.
				int reso = 0 ;
				dclass.Helper_NonQuery("update "+dclass.TablePrefix+"hplayout set enabled='0';");
				reso = dclass.Helper_NonQuery(query);
				if(reso>0 ) {
					dclass.Helper_NonQuery("delete from "+dclass.TablePrefix+"hplayout where enabled='0'");
					return 1;
				} else {
					dclass.Helper_NonQuery("delete from "+dclass.TablePrefix+"hplayout where enabled='1'");
					dclass.Helper_NonQuery("update "+dclass.TablePrefix+"hplayout set enabled='1' where enabled='0';");
				}
			} 
			} catch (Exception ex) {
				//return ex.ToString();
				return 0;
			}
			
			return 0;			
		}				
	
	
		[ WebMethod(Description="getuserForMenu",EnableSession=true)]
		public XmlDocument getuserForMenu(string user){
			DataSet dvs = dclass.ExecuteDataset("select usio.id,usio.username,group_concat(grio.ruolo) as ruoli, " +
			                                    "(select count(*) from "+dclass.TablePrefix +"user_menu where role='user' and  relatedto=usio.username) as mymenu " +
			                                    " from "+dclass.TablePrefix +"utenti as usio " +
			                                    " left join "+dclass.TablePrefix +"utentiruoli as grio on grio.username=usio.username " +
			                                    "where usio.username like '"+user+"%' group by usio.id order by usio.username asc; ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}		
		[ WebMethod(Description="getgroupForMenu",EnableSession=true)]
		public XmlDocument getgroupForMenu(string role){
			DataSet dvs = dclass.ExecuteDataset("select grio.ruolo, grio.punti as punti, grio.dipendenze, grio.security, " +
			                                    "(select count(*) from "+dclass.TablePrefix +"user_menu where role='group' and  relatedto=grio.ruolo) as mymenu " +
			                                    " from "+dclass.TablePrefix +"ruoli as grio " +
			                                    "where grio.ruolo like '"+role+"%' order by grio.ruolo asc; ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	

		[ WebMethod(Description="getrolesDepend",EnableSession=true)]
		public string getrolesDepend(string role){
			object ordata = dclass.HStandard_SC("SELECT dipendenze FROM "+dclass.TablePrefix+"ruoli where ruolo = '"+role+"';");
			if(ordata == null)
				return string.Empty;
			else {
				if(ordata is byte[])
					return System.Text.Encoding.UTF8.GetString( (byte[]) ordata);
				else
					return ordata.ToString();
			}
		}	
		
		
		private string CaricaFigli(DataTable ds, string pos, string tipo) {
			string sons = "";
			DataRow[] dr = ds.Select("figliodi='" + pos+"'");
			if(dr.Length>0) 
				sons +="<ul>";
			for(int i = 0 ;i<dr.Length;i++) {
//				sons+="<li id=\"m"+tipo + dr[i]["id"] + "\">"+dr[i]["nome"];
				sons+="<li id=\"m"+tipo + dr[i]["id"] + "\" rel=\"" +dr[i]["customVoce"]+"\">"+dr[i]["nome"];
				sons+= CaricaFigli(ds,dr[i]["id"].ToString(),tipo );
				sons+="</li>";
			}
			if(dr.Length>0)
				sons+="</ul>";
			return sons;
		}
		private string CaricaFigli2(DataTable ds, string pos, string tipo) {
			string sons = "";
			DataRow[] dr = ds.Select("figliodi='" + pos+"'");
			if(dr.Length>0) 
				sons +="<ul>";
			for(int i = 0 ;i<dr.Length;i++) {
				string id = dr[i]["id"].ToString();
				if(id.IndexOf('_')!=-1)
					id = id.Substring(id.IndexOf('_')+1);
				sons+="<li id=\"m"+tipo + id + "\" rel=\"" +dr[i]["customVoce"]+"\">"+dr[i]["nome"];
				sons+= CaricaFigli2(ds,dr[i]["id"].ToString(),tipo );
				sons+="</li>";
			}
			if(dr.Length>0)
				sons+="</ul>";
			return sons;
		}	
		
		
		[ WebMethod(Description="getMenusforGroup",EnableSession=true)]
		public XmlDocument getMenusforGroup(string role, string depending, string score, string security,string lang) {
			string out_test = "";
			//devo caricare l'elenco delle dipendenze per il menu in azione:
			string dipendenze = string.Empty;
			dipendenze = depending;
			string tempDip =dipendenze.Trim();
			
			dipendenze = role+"," +dipendenze;
			
            if(tempDip.EndsWith(","))
            	tempDip = tempDip.Substring(0,tempDip.Length-1);
            int conto = 0;
            while(tempDip!=string.Empty) {
            	object letto = dclass.HStandard_SC(	
						" select ifnull(mastrole.dipendenze,'') as dipendenze  " +
						" from `"+dclass.TablePrefix+"ruoli` as mastrole " +
						" where mastrole.ruolo = '"+tempDip+"' limit 1; ");
        		if(letto==null) 
        			tempDip = string.Empty;
        		else {
        			if(letto is byte[] )
        				tempDip = System.Text.Encoding.UTF8.GetString((byte[])letto);
        			else
        				tempDip = letto.ToString();
        		}
        		if(tempDip.Trim().Length==0) 
        			tempDip= string.Empty;
        		else
        			dipendenze+= tempDip + ",";
				conto++;            		
           }
			string[] dipolo = new string[0];
			if(dipendenze.Trim().Length>0) {
				if(dipendenze.IndexOf(',')!=-1)
					dipolo = dipendenze.Split(',');
				else
					dipolo = new string[] {dipendenze.Trim()};
			}
			out_test= ACM.cmsarea08.Administration.Core.AdminMenuGenerator.adminMenu.getMainMenu(role,score,dipolo,security,ACM.cmsarea08.Administration.Core.AdminMenuGenerator.MenuModes.EditMode,"editMenu",lang);
			System.Xml.XmlDocument xdoc = new XmlDocument();
			xdoc.LoadXml(out_test);
			return xdoc;
		}

		[ WebMethod(Description="getMenusforGroup2",EnableSession=true)]
		public XmlDocument getMenusforGroup2(string role, string depending, string score, string security,string lang) {
			string out_test = "";
			//devo caricare l'elenco delle dipendenze per il menu in azione:
			string dipendenze = string.Empty;
			dipendenze = depending;
			string tempDip =dipendenze.Trim();
			
			dipendenze = role+"," +dipendenze;
			
            if(tempDip.EndsWith(","))
            	tempDip = tempDip.Substring(0,tempDip.Length-1);
            int conto = 0;
            while(tempDip!=string.Empty) {
            	object letto = dclass.HStandard_SC(	
						" select ifnull(mastrole.dipendenze,'') as dipendenze  " +
						" from `"+dclass.TablePrefix+"ruoli` as mastrole " +
						" where mastrole.ruolo = '"+tempDip+"' limit 1; ");
        		if(letto==null) 
        			tempDip = string.Empty;
        		else {
        			if(letto is byte[] )
        				tempDip = System.Text.Encoding.UTF8.GetString((byte[])letto);
        			else
        				tempDip = letto.ToString();
        		}
        		if(tempDip.Trim().Length==0) 
        			tempDip= string.Empty;
        		else
        			dipendenze+= tempDip + ",";
				conto++;            		
           }
			string[] dipolo = new string[0];
			if(dipendenze.Trim().Length>0) {
				if(dipendenze.IndexOf(',')!=-1)
					dipolo = dipendenze.Split(',');
				else
					dipolo = new string[] {dipendenze.Trim()};
			}
			out_test= ACM.cmsarea08.Administration.Core.AdminMenuGenerator2.adminMenu.processMenu(role,score,dipolo,security,lang,false);
			System.Xml.XmlDocument xdoc = new XmlDocument();
			xdoc.LoadXml(out_test);
			return xdoc;
		}

		[ WebMethod(Description="getMenusforGroupC",EnableSession=true)]
		public XmlDocument getMenusforGroupC(string role, string depending, string score, string security,string lang) {
			string out_test = "";
			//devo caricare l'elenco delle dipendenze per il menu in azione:
			string dipendenze = string.Empty;
			dipendenze = depending;
			string tempDip =dipendenze.Trim();
			
			dipendenze = role+"," +dipendenze;
			
            if(tempDip.EndsWith(","))
            	tempDip = tempDip.Substring(0,tempDip.Length-1);
            int conto = 0;
            while(tempDip!=string.Empty) {
            	object letto = dclass.HStandard_SC(	
						" select ifnull(mastrole.dipendenze,'') as dipendenze  " +
						" from `"+dclass.TablePrefix+"ruoli` as mastrole " +
						" where mastrole.ruolo = '"+tempDip+"' limit 1; ");
        		if(letto==null) 
        			tempDip = string.Empty;
        		else {
        			if(letto is byte[] )
        				tempDip = System.Text.Encoding.UTF8.GetString((byte[])letto);
        			else
        				tempDip = letto.ToString();
        		}
        		if(tempDip.Trim().Length==0) 
        			tempDip= string.Empty;
        		else
        			dipendenze+= tempDip + ",";
				conto++;            		
           }
			string[] dipolo = new string[0];
			if(dipendenze.Trim().Length>0) {
				if(dipendenze.IndexOf(',')!=-1)
					dipolo = dipendenze.Split(',');
				else
					dipolo = new string[] {dipendenze.Trim()};
			}
			out_test= ACM.cmsarea08.Administration.Core.AdminMenuGenerator2.adminMenu.processMenu(role,score,dipolo,security,lang,true,true);
			System.Xml.XmlDocument xdoc = new XmlDocument();
			xdoc.LoadXml(out_test);
			return xdoc;
		}


	
		[ WebMethod(Description="removeMenuVoce",EnableSession=true)]
		public string removeMenuVoce(string id, string tipo,string proprietario, string role) {
			string exQuery = "";
			try {
			bool btipo = false;
			bool.TryParse(tipo, out btipo);
			if(btipo == true) {
				
				//voce custom:
				if(id.StartsWith("C")) {
					exQuery+= "BLOCCO C\n\ndelete from "+dclass.TablePrefix +"user_menu where " +
					                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and id='" +id.Substring(1)+"'\n";
					int ireso = dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"user_menu where " +
					                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and id='" +id.Substring(1)+"'");
					exQuery+="delete from "+dclass.TablePrefix +"user_menu where " +
					                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and sonof='" +id+"'\n";
					ireso += dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"user_menu where " +
					                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and sonof='" +id+"'");
					return (ireso>0?"OK":"NO");
				}
				exQuery+="BLOCCO C2\n\ndelete from "+dclass.TablePrefix +"user_menu where " +
				                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and admin_menu='" +id+"'";
				int reso = dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"user_menu where " +
				                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and admin_menu='" +id+"'");
				exQuery+="\n\ndelete from "+dclass.TablePrefix +"user_menu where " +
				                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and sonof='" +id+"'";
				
				reso += dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"user_menu where " +
				                                " role ='"+role+"' and relatedto='"+proprietario+"' and operation='A' and sonof='" +id+"'");
				
				return (reso>0?"OK":"NO");
			} else {
				exQuery+="BLOCCO ADAD:\n\ninsert into "+dclass.TablePrefix +"user_menu (`role`,`relatedto`,`admin_menu`,`position`,`id`,`order`,`sonof`,`operation`,`nomevoce`,`lang`) \nselect " +
					"'"+role+"' as `role`, '"+proprietario+"' as `relatedto`, miunu.id as `admin_menu`, 'top' as `position`, '-1' as `id`, miunu.ordine as `order`," +
					" figliodi as `sonof`, 'R' as `operation`, miunu.nome as `nomevoce`, miunu.lingua as `lang` from "+dclass.TablePrefix +"admin_menu as miunu where " +
					" miunu.id = "+id+" or miunu.figliodi="+id+" ; ";
				
				//in questo caso aggiungi righe con "R";
				string insq = "insert into "+dclass.TablePrefix +"user_menu (`role`,`relatedto`,`admin_menu`,`position`,`id`,`order`,`sonof`,`operation`,`nomevoce`,`lang`) \nselect " +
					"'"+role+"' as `role`, '"+proprietario+"' as `relatedto`, miunu.id as `admin_menu`, 'top' as `position`, '-1' as `id`, miunu.ordine as `order`," +
					" figliodi as `sonof`, 'R' as `operation`, miunu.nome as `nomevoce`, miunu.lingua as `lang` from "+dclass.TablePrefix +"admin_menu as miunu where " +
					" (miunu.id = "+id+" or miunu.figliodi="+id+") and miunu.enabled ='1' ; ";
				//exQuery = insq;
				int reso = dclass.ExecuteScalar(insq);
				return (reso>0?"OK":"NO");
			}
			}catch (Exception ex) {
				return ex.ToString() + "\n" + exQuery;
			}
		}

		[ WebMethod(Description="renMenuVoce",EnableSession=true)]
		public string renMenuVoce(string nomevoce, string id,string proprietario, string role) {
			if(HttpUtility.UrlDecode(nomevoce).Trim()=="") return "NO";
			nomevoce = HttpUtility.HtmlEncode(HttpUtility.UrlDecode(nomevoce).Trim().Replace("'","\'"));
			string eQuery = "update "+dclass.TablePrefix +"user_menu set `nomevoce`='"+nomevoce+"' " + 
				" where " + (id.ToLower().StartsWith("c")?
				             ("id='" + id.Substring(1) + "'"):
				             ("admin_menu='" + id + "'")
				            ) +
				" and `relatedto`='"+proprietario+"' and `role`='"+role+"' ";
			int reso = dclass.ExecuteScalar(eQuery);
				return (reso>0?"OK":"NO");
		}

			
		[ WebMethod(Description="addMenuVoce",EnableSession=true)]
		public string addMenuVoce(string id, string padre,string proprietario, string role,string tipo) {
			string exQuery = "";
			try {
				//devi controllare se ho un id di rimozione su ID
				bool foundLine = false;
				if(tipo.ToLower()!="true") {
					//check se esiste una chiave R con stesse dipendenze:
					object o = dclass.HStandard_SC("select count(admin_menu) from "+dclass.TablePrefix+"user_menu where " +
					                               "( (admin_menu='"+id+"' and sonof='"+padre+"') or (sonof='"+id+"') ) and " +
					                               " `operation`='R' and `role`='"+role+"' and `relatedto`='"+proprietario+"' ;");
					if(o!=null) {
						//allora esistono record:
						string num ="";
						if(o is byte[]) num = System.Text.Encoding.UTF8.GetString((byte[]) o);
						else num = o.ToString();
						if(num!="0")
							foundLine=true;
						else
							foundLine=false;
					}
				}
				//in questo caso aggiungi righe con "R";
				string insq ="";
				if(foundLine) {
					insq = "delete from "+dclass.TablePrefix +"user_menu where " +
                           "( (admin_menu='"+id+"' and sonof='"+padre+"') or (sonof='"+id+"') ) and " +
                           " `operation`='R' and `role`='"+role+"' and `relatedto`='"+proprietario+"' ";
				} else {
					insq = "insert into "+dclass.TablePrefix +"user_menu (`role`,`relatedto`,`admin_menu`,`position`,`id`,`order`,`sonof`," +
						"`operation`,`nomevoce`,`lang`) \nselect " +
						"'"+role+"' as `role`, '"+proprietario+"' as `relatedto`, miunu.id as `admin_menu`, 'top' as `position`, '-1' as `id`, " +
						"miunu.ordine as `order`," +
						" '"+padre+"' as `sonof`, 'A' as `operation`, miunu.nome as `nomevoce`, miunu.lingua as `lang` from "+dclass.TablePrefix +"admin_menu as miunu where " +
						" (miunu.id = "+id+" ) and enabled='1' ; ";
				}
				exQuery = insq;
				int reso = dclass.ExecuteScalar(insq);
				return (reso>0?"OK":"NO");
			}catch (Exception ex) {
				return ex.ToString() + "\n" + exQuery;
			}
		}
		
		[ WebMethod(Description="addUserMenuVoce",EnableSession=true)]
		public string addUserMenuVoce(string nomevoce, string padre,string proprietario, string role) {
			string exQuery = "";
			try {
				string generatedID ="";
				nomevoce = HttpUtility.HtmlEncode(HttpUtility.UrlDecode(nomevoce).Trim().Replace("'","\'"));
				//getLastID
				object oid = dclass.ExecuteScalar_Logged("select max(id) from "+dclass.TablePrefix +"user_menu ;",out generatedID);
				if(oid==null) {
					generatedID = "0";
				} else {
					if(oid is byte[]) 
						generatedID = System.Text.Encoding.UTF8.GetString((byte[]) oid);
					else
						generatedID = oid.ToString();
				}
				int myID = 0;
				Int32.TryParse(generatedID,out myID);
				myID+=1;
				if(padre.Trim()=="")
					padre = "-1";
				//in questo caso aggiungi righe con "R";
				string insq = "insert into "+dclass.TablePrefix +"user_menu (`role`,`relatedto`,`admin_menu`,`position`,`id`,`order`,`sonof`,`operation`,`nomevoce`,`lang`) \nVALUES(" +
					"'"+role+"', '"+proprietario+"', '0','top', '"+myID.ToString()+"',0," +
					" '"+padre+"', 'A', '"+nomevoce+"',''); ";
				exQuery = insq;
				int reso = dclass.ExecuteScalar(insq);
				return (reso>0?"OK":"NO");
			}catch (Exception ex) {
				return ex.ToString() + "\n" + exQuery;
			}
		}
		[ WebMethod(Description="EliminaRuoloCont",EnableSession=true)]
		public int EliminaRuoloCont(string idtipo,string ruolo){
			
			
			if(idtipo.Length<2)
				return -1;
			string tipo = idtipo.Substring(0,1);
			string id = idtipo.Substring(1);
			if(tipo.Length!=1 || id.Trim()=="")
				return -1;
			int reso = dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"contenutiruoli where tipo='" + tipo + "' and id='" + id +
			                                    "' and ruolo='" + ruolo + "' limit 1; ");
			
			
			return reso;			
		}	
		[ WebMethod(Description="EliminaRuoloUser",EnableSession=true)]
		public int EliminaRuoloUser(string user,string ruolo){
			
			
			if(user.Trim()=="" || ruolo.Trim()=="")
				return -1;
			
			
			int reso = dclass.ExecuteScalar("delete from "+dclass.TablePrefix +"utentiruoli where username='" + user + 
			                                "' and ruolo='" + ruolo + "' limit 1; ");
			
			
			return reso;			
		}	

	
		[ WebMethod(Description="getRolesList",EnableSession=true)]
		public XmlDocument getRolesList(string filt){
			string filter = "";
			if(filt!="all" && filt.IndexOf(',')!=-1 ) {
				int start = -1;
				int end   = -1;
				start = Convert.ToInt32(filt.Substring(0, filt.IndexOf(',')));
				end   = Convert.ToInt32(filt.Substring(filt.IndexOf(',')+1));

				for(int i= start; i<=end;i++) {
					filter+= " ruolo like '"+(char)i+"%' or";
				}
				filter = filter.Substring(0,filter.Length-2);
				filter = " (" + filter + ") ";
			}
			
			
			DataSet dvs = dclass.ExecuteDataset("SELECT ruolo,dipendenze FROM itant_ruoli where " +
			                                    "enabled='1' " +
			                                    (filter!=""?("and " + filter):"")
			                                    + " order by ruolo asc ");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	
	
		[ WebMethod(Description="getModuleList",EnableSession=true)]
		public XmlDocument getModuleList(){
			DataSet dvs = dclass.ExecuteDataset("" +
			                    " SELECT modio.id, modio.titolo, admin_tool,public_tool  FROM itant_moduli as modio " +
								" left join itant_componenti as compio on  modio.id_componente = compio.id " +
								" where modio.enabled='1' and ( " +
								"        ((not isnull(admin_tool)) and admin_tool<>'' ) or " +
								"        ((not isnull(public_tool)) and public_tool<>'') " +
								"                            ) " +
								" order by titolo asc;");
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}	

		
		[ WebMethod(Description="getUserPanel",EnableSession=true)]
		public XmlDocument getUserPanel( string roleName){
			string query = "";
			//calcolo delle dipendenze:
			string dipendenze = string.Empty;
			string tempDip =roleName+",";
			dipendenze = roleName+",";
            if(tempDip.EndsWith(","))
            	tempDip = tempDip.Substring(0,tempDip.Length-1);
            int conto = 0;
            while(tempDip!=string.Empty) {
            	object letto = dclass.HStandard_SC(	
						" select ifnull(mastrole.dipendenze,'') as dipendenze  " +
						" from `"+dclass.TablePrefix+"ruoli` as mastrole " +
						" where mastrole.ruolo = '"+tempDip+"' limit 1; ");
        		if(letto==null) 
        			tempDip = string.Empty;
        		else {
        			if(letto is byte[] )
        				tempDip = System.Text.Encoding.UTF8.GetString((byte[])letto);
        			else
        				tempDip = letto.ToString();
        		}
        		if(tempDip.Trim().Length==0) 
        			tempDip= string.Empty;
        		else
        			dipendenze+= tempDip + ",";
				conto++;            		
           }
			string[] dipolo = new string[0];
			if(dipendenze.Trim().Length>0) {
				if(dipendenze.IndexOf(',')!=-1)
					dipolo = dipendenze.Split(',');
				else
					dipolo = new string[] {dipendenze.Trim()};
			}			
			
			string dipePart = "";
			for(int i = 0; i<dipolo.Length; i++) {
				if(dipolo[i].Trim()=="") continue;
				dipePart += " rolename='" + dipolo[i] + "' or";
			}
			if(dipePart.Length>0) {
				dipePart = "( " + dipePart.Substring(0,dipePart.Length-2) + " ) AND ";
			} else dipePart = string.Empty;
			
			query =
				"(select `shortname`, " +
				" concat(`paneltype`,'_',if(`paneltype`='D',`defaulturl`,cast(`moduleinstance` as char) ) ) as valore ,  `order`,'0' as enabled from {0}userpanel " +
				"where "+dipePart+"  rolename<>'{1}' )";
			query += "union distinct (select `shortname`, " +
				" concat(`paneltype`,'_',if(`paneltype`='D',`defaulturl`,cast(`moduleinstance` as char) ) )  as valore , " +
				"`order`,'1' as enabled from {0}userpanel where rolename='{1}' order by `order` asc); ";
			//HttpContext.Current.Response.Write("SONO QUI: " +  string.Format(query,dclass.TablePrefix,roleName) );
			DataSet dvs = dclass.ExecuteDataset(string.Format(query,dclass.TablePrefix,roleName));
			if(dvs == null)
				return new XmlDocument();
	        XmlDocument outd = new XmlDocument();
	        outd.LoadXml(dvs.GetXml());
			return outd;			
		}		
		
		[ WebMethod(Description="setUserPanel",EnableSession=true)]
		public XmlDocument setUserPanel(string panelList, string roleName){
			XmlDocument outd = new XmlDocument();
			string[] valori = new string[0];
			if(string.IsNullOrEmpty(panelList)) {
				outd.InnerXml = "<response>NO PANEL LIST</response>";
				return outd;
			}
			if(panelList.Trim()=="" || panelList==string.Empty) {
				outd.InnerXml = "<response>NO PANEL LIST</response>";
				return outd;
			}
			if(string.IsNullOrEmpty(roleName)) {
				outd.InnerXml = "<response>NO roleName</response>";
				return outd;
			}
			if(roleName.Trim()=="" || roleName==string.Empty) {
				outd.InnerXml = "<response>NO roleName</response>";
				return outd;
			}
			if(panelList.IndexOf('#')==-1) 
				valori = new string[1] {panelList.Trim()};
			else
				valori =panelList.Trim().Split('#');
			
			//query
			string querySTART = "";
			string queryEX = "";
			string queryERR = "";
			string queryDEL0 = "";
			string queryDEL1 = "";
			querySTART = "update {0}userpanel set preDelete='1' where rolename = '{1}' and preDelete='0' ;";
			queryERR = "update {0}userpanel set preDelete='0' where rolename = '{1}' and preDelete='1' ;";
			queryDEL1 = "delete from {0}userpanel where rolename = '{1}' and preDelete='1' ;";
			queryDEL0 = "delete from {0}userpanel where rolename = '{1}' and preDelete='0' ;";
			
			int order = 0;
			foreach(string x in valori) {
				string tipo = "";
				string valore ="";
				string shortName = "";
				if(x.IndexOf('_')==-1) continue;
				if(x.IndexOf('[')==-1) continue;
				tipo = x.Substring(0,x.IndexOf('_'));
				valore = x.Substring(x.IndexOf('_')+1,x.IndexOf('[') - x.IndexOf('_')-1);
				shortName = x.Substring(x.IndexOf('[')+1);
				queryEX += " insert into {0}userpanel (`rolename`, `paneltype`,`moduleinstance`,`defaulturl`,`order`,`preDelete`,`shortname`) values(";	
				queryEX += " '{1}','"+tipo+"',"+(tipo.ToLower()!="d"?valore:"-1")+",'"+(tipo.ToLower()=="d"?valore:"")+"',"+order+",'0','"+shortName+"' ";
				queryEX += ");\n";
				order++;
			}
			//esecuzione query:
			int reso = -1;
			//preparo eventuali valori
			dclass.ExecuteScalar(string.Format(querySTART,dclass.TablePrefix,roleName) );
			//eseguo tutto.
			if(queryEX.Trim()!="") {
				try {
				reso = dclass.ExecuteScalar(string.Format(queryEX,dclass.TablePrefix,roleName) );
				} catch {
					outd.InnerXml = "<response>"+string.Format(queryEX,dclass.TablePrefix,roleName)+"</response>";
					return outd;
				}
			} else
				reso =1;
			if(reso<=0) {
				//errore ci fu
				dclass.ExecuteScalar(string.Format(queryDEL0,dclass.TablePrefix,roleName) );
				dclass.ExecuteScalar(string.Format(queryERR,dclass.TablePrefix,roleName) );
				outd.InnerXml = "<response>NO INSERT</response>";
				return outd;
			}	
			dclass.ExecuteScalar(string.Format(queryDEL1,dclass.TablePrefix,roleName) );
			outd.InnerXml = "<response>OK</response>";
			return outd;
		}	
		
	
	
		
	}
	
}


/*
 * DROP TABLE IF EXISTS `cms`.`itant_ruoli`;
CREATE TABLE  `cms`.`itant_ruoli` (
  `ruolo` varchar(45) NOT NULL,
  `descrizione` text NOT NULL,
  `enabled` enum('0','1') NOT NULL default '1',
  `data_ins` datetime NOT NULL default '1800-01-01 00:00:59',
  `data_mod` datetime NOT NULL default '1800-01-01 00:00:59',
  `id_componente` int(11) NOT NULL default '-1',
  `dipendenze` text NOT NULL,
  PRIMARY KEY  (`ruolo`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;*/
